﻿namespace dotnet_notes.Filters
{
    /// <summary>
    /// 全局 Action 响应包装过滤器
    /// </summary>
    public class GlobalResponseFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync
            (ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 执行前

            // 执行
            var resultContext = await next();

            // 执行后
            switch (resultContext.Result)
            {
                case OkResult:
                    resultContext.Result = new ObjectResult(new ResponseResult
                    {
                        Success = true,
                        Result = null
                    });
                    break;

                case OkObjectResult:
                    resultContext.Result = new ObjectResult(new ResponseResult
                    {
                        Success = true,
                        Result = (resultContext.Result as OkObjectResult).Value
                    });
                    break;

                case UnauthorizedResult: break;
                case FileStreamResult: break;
                default: break;
            }
        }
    }
}
